package com.gbco.intelligentpush.service;

import com.alibaba.fastjson.JSONObject;
import com.gbco.intelligentpush.entity.OpenID;
import com.gbco.intelligentpush.entity.UserINFO;
import com.gbco.intelligentpush.entity.menuentity.AccessToken;
import com.gbco.intelligentpush.entity.menuentity.JsApiTicket;
import com.gbco.intelligentpush.entity.messageModel.ModelMessage;
import com.gbco.intelligentpush.utils.HttpUtil;
import com.gbco.intelligentpush.utils.JedisAdapter;
import com.gbco.intelligentpush.utils.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * @ Author     ：tk.
 * @ Date       ：Created in 11:41 2020/05/23
 * @ Description：Wx服务层
 * @ Modified By：
 * @Version: $
 */
@Service
@Slf4j
public class WxService {

    @Autowired
    JedisAdapter jedisAdapter;

    @Value("${wx.ACCESSTOKENKEY}")
    private String ACCESSTOKENKEY ;

    @Value("${wx.accesstoken_url}")
    private String accesstoken_url;

    @Value("${wx.APPID}")
    private String APPID;

    @Value("${wx.APPSECRET}")
    private String APPSECRET;

    @Value("${wx.GET_USERINFO_URL}")
    private String GET_USERINFO_URL;

    @Value("${wx.PUSH_URL}")
    private String PUSH_URL;

    @Value("${Jedis.HFMD_JSAPI_TICKET_KEY}")
    private String HFMD_JSAPI_TICKET_KEY;

    //发送模板消息
    public String pushMessage(String ACCESSTOKEN , ModelMessage modelMessage){
        String url = PUSH_URL.replaceAll("ACCESS_TOKEN",ACCESSTOKEN);
        String result = HttpUtil.post(url, JSONObject.toJSONString(modelMessage));
        return result;
    }

    //拿取JSApi_ticket
    public String getJSAPITICKET(String ACCESSTOKEN){
        String js_api_ticket = jedisAdapter.get(HFMD_JSAPI_TICKET_KEY);
        if (js_api_ticket==null){
            String returnResult = WxUtil.getJSAPITICKET(ACCESSTOKEN);
            JsApiTicket jsApiTicket = JSONObject.parseObject(returnResult,JsApiTicket.class);
            if (jsApiTicket.getTicket()==null){
                log.error("获取JSAPITICKET失败 返回结果："+returnResult);
                return null;
            }else{
                js_api_ticket = jsApiTicket.getTicket();
            }
            log.info("成功从微信服务器获取到JSAPITICKET："+returnResult);
            jedisAdapter.setex(HFMD_JSAPI_TICKET_KEY,6900,js_api_ticket);
        }else
            log.info("成功从缓存获取到JSAPITICKET");
        return js_api_ticket;
    }


    //拿取Access_token(全局的ACCESSTOKEN)
    public String getAccessToken(){
        String access_token = jedisAdapter.get(ACCESSTOKENKEY);
        if (access_token==null){
            String returnResult = WxUtil.getAccesstoken();
            AccessToken accessToken = JSONObject.parseObject(returnResult,AccessToken.class);
            if (accessToken.getAccess_token()==null){
                log.error("获取ACCESSTOKEN失败 返回结果："+access_token);
                return null;
            }else
                access_token = accessToken.getAccess_token();
            log.info("成功从微信服务器获取到全局ACCESSTOKEN");
            jedisAdapter.setex(ACCESSTOKENKEY,6900,access_token);
        }else{
            log.info("成功从缓存获取到ACCESSTOKEN");
        }
        return access_token;
    }

    //分两步 获取openid  获取userifo
    public UserINFO getUserINFOFromCode(String code){
        UserINFO userINFO = null;
        OpenID openID;
        String openid = getaccesstoken(code),userinfo;
        openID = JSONObject.parseObject(openid).toJavaObject(OpenID.class);
        String accesstoken = openID.getAccess_token();
        if (!StringUtils.isNoneBlank(accesstoken)){
            log.error("GetUserINFOFromCode时获取openid出错:"+openid);
            return userINFO;
        } else
            userinfo = getUserINFO(openID.getOpenid(),accesstoken);
        userINFO = JSONObject.parseObject(userinfo).toJavaObject(UserINFO.class);
        if (userINFO.getOpenid()==null){
            log.error("GetUserINFOFromCode时获取userINFO出错:"+userinfo);
            return null;
        }
        return userINFO;
    }

    //拿取access_token(网页授权的 access_token)
    public String getaccesstoken(String code){
        String url = accesstoken_url.replaceAll("APPID",APPID).replaceAll("SECRET",APPSECRET).replaceAll("CODE",code);
        String result ;
        if(!StringUtils.isNoneBlank(url)) {
            log.error("拿取Access_token(网页授权的)失败:url错误"+url);
            return null;
        } else
            result = HttpUtil.get(url);
        return result;
    }

    //拿取用户信息 accesstoken 为网页授权的
    public String getUserINFO(String openid , String access_token){
        String url = GET_USERINFO_URL.replaceAll("ACCESS_TOKEN",access_token).replaceAll("OPENID",openid);
        String result ;
        if (!StringUtils.isNoneBlank(url)){
            log.error("用户:"+openid+"getUSERINFO失败:url错误");
            return null;
        } else
            result = HttpUtil.get(url);

        return result;
    }


}
